package cn.tedu.weibo.controller;

import cn.tedu.weibo.common.response.JsonResult;
import cn.tedu.weibo.common.response.StatusCode;
import cn.tedu.weibo.pojo.dto.UserLoginDTO;
import cn.tedu.weibo.pojo.dto.UserRegDTO;
import cn.tedu.weibo.pojo.vo.UserVO;
import cn.tedu.weibo.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("reg")
    public JsonResult register(@RequestBody UserRegDTO userRegDTO){
        log.debug("注册用户信息{}" + userRegDTO);
        int res = userService.register(userRegDTO);
        if(res == 0){
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXIST);
        }
        return new JsonResult(StatusCode.OPERATION_SUCCESS);
    }
    @ApiOperation("用户登录")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("用户登录信息{}" + userLoginDTO);
        UserVO userVO = userService.login(userLoginDTO);
        if(userVO == null){
            return new JsonResult(StatusCode.UNAME_PWD_ERROR);
        }
        session.setAttribute("user",userVO);
        return new JsonResult(StatusCode.OPERATION_SUCCESS);
    }

    @ApiOperation("用户状态")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        return new JsonResult(StatusCode.OPERATION_SUCCESS,userVO);
    }

    @ApiOperation("用户注销")
    @GetMapping("logout")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return new JsonResult(StatusCode.OPERATION_SUCCESS);
    }
}